package com.ztgf.shopping.service.shop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.shopping.models.bo.shop.ShopPaymentCardApiSaveBO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.ztgf.shopping.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.shopping.mapper.shop.ShopPaymentCardMapper;
import com.ztgf.shopping.models.service.shop.IShopPaymentCardService;
import com.ztgf.shopping.models.bo.shop.ShopPaymentCardSaveBO;
import com.ztgf.shopping.models.dto.shop.ShopPaymentCardDTO;

/**
 * 用户付款账号表控制器
 *
 * @author zhanghualang
 * @Date 2020-05-27 14:32:11
 */
@DubboService
public class ShopPaymentCardServiceImpl extends ServiceImpl<ShopPaymentCardMapper, ShopPaymentCardDTO> implements IShopPaymentCardService{
    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(ShopPaymentCardSaveBO saveBO) {
        //去重
        Wrapper<ShopPaymentCardDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("bank_card_no", saveBO.getBankCardNo());
        ShopPaymentCardDTO shopPaymentCardDTO = this.selectOne(wrapper);

        if (shopPaymentCardDTO != null){
            return false;
        }

        ShopPaymentCardDTO dto = new ShopPaymentCardDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public boolean updateDefault(Long id) {
        ShopPaymentCardDTO shopPaymentCardDTO = this.selectById(id);
        ShopPaymentCardDTO newPaymentCardDTO = new ShopPaymentCardDTO();
        Wrapper<ShopPaymentCardDTO> wrapper = new EntityWrapper<>();
        //获取旧的dto
        ShopPaymentCardDTO oldshopPaymentCardDTO = this.selectOne(wrapper.eq("shop_id", shopPaymentCardDTO.getShopId()).eq("is_default", 1));
        if (oldshopPaymentCardDTO != null){
            ShopPaymentCardDTO oldPaymentCardDTO = new ShopPaymentCardDTO();
            oldPaymentCardDTO.setIsDefault(0);//改为不默认；
            oldPaymentCardDTO.setId(oldshopPaymentCardDTO.getId());
            this.updateById(oldPaymentCardDTO);
        }
        newPaymentCardDTO.setIsDefault(1);//改为默认
        newPaymentCardDTO.setId(id);
        return this.updateById(newPaymentCardDTO);
    }
}
